const reply = require('../utils/reply');
const app = require('../app');
const exec = require('child_process').exec;
const request = require('request');

const TaskController = {
    /**
     * {name, lang, timezone, proxy, android, other}
     *
     * other: {
     *     android_id,
     *     version,
     *     sdk_version,
     *     device_name,
     *     operator_name,
     *     operator_code,
     *     package_name,
     *     network,
     *     timezone,
     *     lang
     * }
     *
     * @param ctx
     * @param next
     * @returns {Promise<void>}
     */
    start: async (ctx, next) => {

        // 接收参数
        let data = ctx.request.body;
        let unlockId = data.unlock_id;
        let proxy = data.proxy;
        let other = data.other;
        // let other = "ok";
        data = JSON.parse(other);

        // let cmdStr = "node test.js";
        let cmdStr = "node ";

        // 获取单子
        await request({
                url: "http://127.0.0.1:8090/server/get_operator",
                method: 'GET',
                qs: {
                    operator_code: data.operator_code,
                    package_name: data.package_name,
                    version: data.version,
                    device_id: data.android_id,
                    sdk_version: data.sdk_version,
                    device_name: data.device_name,
                    network: data.network,
                    timezone: data.timezone,
                    lang: data.lang
                }
            },
            async (error, response, body) => {
                // 完成之后 回传数据给子服务器
                // 进行任务分发启动
                let errMsg = null;
                let responseData = JSON.parse(response.body);
                // 如果单子获取出错
                if (responseData.code !== 0) {
                    // 单子请求未成功，则获取报错信息，然后之后随之返回给调用 的子服务器
                    errMsg = responseData.msg;
                    await request({
                        url: 'http://127.0.0.1:8095/unlock_request',
                        body: {code: 1, msg: errMsg, data: {id: parseInt(unlockId), info: errMsg}},
                        method: 'POST',
                        json: true
                    });
                    return
                }

                // 请求成功，则获取单子路径
                cmdStr = cmdStr + responseData.data.path;
                cmdStr = cmdStr + ` ${data.lang} ${data.timezone} ${proxy} ${data.android_id} ${other}`;

                // 执行脚本
                await exec(cmdStr, async (err, stdout, stderr) => {
                    app.logger.debug("end script");
                    if (err) {
                        app.logger.info(err);
                        app.logger.debug(err);
                    } else {
                        app.logger.info(stdout);
                        app.logger.debug(stdout);
                    }

                    // 脚本执行完毕 成功之后的回调，回调解锁接口，解锁阻塞
                    await request({
                        url: "http://127.0.0.1:8095/unlock_request",
                        method: 'POST',
                        body: {code: 0, msg: '', data: {id: parseInt(unlockId), info: "success"}},
                        json: true
                    }, (error, response, body) => {
                        app.logger.info(response.body)
                    })
                });
            });

        await reply(ctx, null, function (ctx, result) {
            result.data = data;
            ctx.json(result);
        });
    }
};

module.exports = TaskController;
